<template>
  <div class="index" id="index">
    <div class="header">
      <div class="title" style="">
        俯瞰 OVERLOOK
        <el-button
          type="primary"
          @click="gotoHome"
          class="toHomeButton"
          style=""
          >退出登录</el-button
        >
      </div>
    </div>
    <div class="line"></div>
    <el-container>
      <el-aside>
        <el-menu
          class="el-menu-vertical-demo"
          :default-active="this.$route.path"
          router="true"
        >
          <el-menu-item index="/checkSystem">
            <div style="text-align: left; margin-left: 20px">
              <i class="el-icon-menu"></i>
              <span slot="title">系统几何级校正</span>
            </div>
          </el-menu-item>
          <el-menu-item index="/checkphoto">
            <div style="text-align: left; margin-left: 20px">
              <i class="el-icon-menu"></i>
              <span slot="title">控制点几何校正</span>
            </div>
          </el-menu-item>
          <el-menu-item index="/toGCPEditor">
            <div style="text-align: left; margin-left: 20px">
              <i class="el-icon-setting"></i>
              <span slot="title">控制点标注采集</span>
            </div>
          </el-menu-item>
          <el-menu-item index="/index">
            <div style="text-align: left; margin-left: 20px">
              <i class="el-icon-menu"></i>
              <span slot="title">图像重建与分解</span>
            </div>
          </el-menu-item>
          <el-menu-item index="/showMap">
            <div style="text-align: left; margin-left: 20px">
              <i class="el-icon-menu"></i>
              <span slot="title">数据查看与呈现</span>
            </div>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <!-- <h2>Welcome !</h2>
        <p>
          请点击按钮“选择图像或GCP”来选择图像： <br />To create a map, press the
          "Select Images and GCP" button, or drag and drop some images into a
          project. <br />You need at least 5 images Images must overlap by 65%
          or more <br />For great 3D, images must overlap by 83% A GCP file is
          optional, but can increase georeferencing accuracy
        </p> -->
        <el-card class="card newProject" @click.native="dialogVisible = true">
          <div>新建项目</div>
          <div><i class="el-icon-plus icon"></i></div>
        </el-card>
        <!-- <div class="createProject">
          <div class="cratePro-font" @click="dialogVisible = true">
            <h1>新建项目</h1>
            <div class="plus-icon"><i class="el-icon-plus icon"></i></div>
          </div>
        </div> -->
        <el-card
          class="card project"
          v-for="(pro, index) in projectList"
          :key="index"
        >
          <div slot="header" class="header">
            {{ pro.proTitle }}
          </div>
          <div class="content">
            <div class="description">
              {{ pro.proDescribe }}
            </div>
            <div class="choice">
              <div class="fileBox">
                上传文件
                <input
                  id="file"
                  type="file"
                  name="image"
                  multiple="multiple"
                  class="fileList"
                />
              </div>
              <el-select v-model="value" placeholder="上传文件格式">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <el-progress
              :percentage="pro.percentage"
              v-if="pro.percentage < 100"
              class="progress"
            ></el-progress>
            <el-progress
              :percentage="pro.percentage"
              status="success"
              class="progress"
              v-else
            ></el-progress>
            <div class="option">
              <el-link type="primary" @click="uploadFile(pro, index)"
                >上传</el-link
              >
              <el-link type="success" @click="gotoShowMap(pro)">查看</el-link>
              <el-dropdown>
                <el-link type="warning">
                  下载
                  <!-- <i class="el-icon-arrow-down el-icon--right"></i> -->
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="downloadPhoto(pro)"
                    >下载正射影像图</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="downloadZip(pro)"
                    >下载瓦片图像集</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <el-link type="danger" @click="deleteProject(pro)">删除</el-link>
            </div>
          </div>
        </el-card>

        <!-- <div class="projects" v-for="(pro, index) in projectList" :key="index">
          <div style="display: flex">
            <div class="titleAndDiscribes">
              <div class="titles">
                <h2>{{ pro.proTitle }}</h2>
              </div>
              <div class="describes" style="color: rgb(160, 160, 160)">
                {{ pro.proDescribe }}
              </div>
            </div>
            <div class="uploadAndShowMap"> -->
        <!-- <input
                type="file"
                accept="image/*"
                @change="getFile2($event)"
                multiple
                class="upload-demo"
              /> -->
        <!-- <input
                id="file"
                type="file"
                name="image"
                multiple="multiple"
                class="fileList"
              /> -->

        <!-- <div class="file-btn">
                选择文件
                <input
                  id="file"
                  type="file"
                  name="image"
                  multiple="multiple"
                  class="inputButton"
                />
              </div> -->

        <!-- <el-button
                class="uploadButton"
                @click="uploadFile(pro, index)"
                type="primary"
                size="small"
                >上传图片</el-button
              > -->
        <!-- <el-button
                @click="showResult"
                size="small"
                type="success"
                class="resultButton"
                v-if="pro.percentage < 100"
                disabled
                >查看结果</el-button
              > -->
        <!-- <el-button
                @click="gotoShowMap(pro)"
                size="small"
                type="success"
                class="resultButton"
                >查看结果</el-button
              >
              <el-dropdown size="small" class="downloadResult">
                <el-button type="primary" size="small">
                  下载结果<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="downloadPhoto"
                    >下载tiff图</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="downloadZip"
                    >下载完整结果</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <el-button
                @click="deleteProject(pro)"
                size="small"
                type="warning"
                class="resultButton"
                >删除项目</el-button
              >
            </div>
          </div>

          <el-progress
            :percentage="pro.percentage"
            v-if="pro.percentage < 100"
            class="progress"
          ></el-progress>
          <el-progress
            :percentage="pro.percentage"
            status="success"
            class="progress"
            v-else
          ></el-progress>
        </div> -->

        <!-- <input type="file" accept="image/*" /> -->

        <el-dialog title="项目信息" :visible.sync="dialogVisible" width="30%">
          <h3 style="margin-top: 10px">请输入项目名称</h3>
          <el-input placeholder="请输入内容" v-model="projectTitle" clearable>
          </el-input>
          <h3>请输入项目描述</h3>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="projectDiscribe"
          >
          </el-input>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelCreate">取 消</el-button>
            <el-button type="primary" @click="confirmCreate">确 定</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<style src="../assets/css/Index.css" scoped >
</style>

<script>
import axios from "axios";
import { request, request1 } from "../network/request.js";
import { fileUpload } from "../network/request.js";
import { ElMessage } from "element-ui";
import { MessageBox } from "element-ui";
import { h } from "element-ui";
export default {
  data() {
    return {
      // loading: true,
      value: "",
      options: [
        {
          value: "选项一",
          label: "仅图片",
        },
        {
          value: "选项二",
          label: "图片与gcp文件",
        },
        {
          value: "选项三",
          label: "图片与geo文件",
        },
      ],
      //uploadActionUrl: "http://101.200.193.250:8000/receiveImg",
      //uploadActionUrl: "https://jsonplaceholder.typicode.com/posts/",
      uploadActionUrl: "http://10.132.20.144/task/new",
      fileList: [],
      //percentage: 0,
      timer: null,
      projectTitle: "",
      projectDiscribe: "",
      dialogVisible: false,
      projectList: [],
      fileData: new FormData(),
      file: "",
      testuuid: "e228396d-39a9-438b-aefb-bf8cf02d0efa",
    };
  },
  methods: {
    async uploadFile(pro, index) {
      var uuid;
      var files = document.getElementsByClassName("fileList")[index].files;
      console.log(files);

      var images = new FormData();
      //add options:tiles
      var options = [{ name: "tiles", value: true }];
      for (let i = 0; i < options.length; i++) {
        for (let key in options[i]) {
          images.append(`options[${i}][${key}]`, options[i][key]);
        }
      }

      //add name
      var name = pro.name;
      images.append("name", name);

      //add images
      for (var i = 0; i < files.length; i++) {
        images.append("images", files[i]);
      }

      console.log(images);

      this.$message({
        message: "上传成功",
        type: "success",
      });
      await axios
        .post("http://10.132.20.144:3000/task/new", images)
        .then(function (response) {
          //成功时服务器返回 response 数据
          console.log(response);
          console.log(response.data.uuid);
          // uuid = response.data.uuid;

          pro.uuid = response.data.uuid;
        })
        .catch(function (error) {
          console.log(error);
        });
      console.log(pro);
      console.log(pro.uuid);
      this.setUuid(pro);
      var flag = 1;
      this.getProgress(pro, flag);
    },

    setUuid(pro) {
      process = {
        method: "post",
        data: {
          id: pro.id,
          uuid: pro.uuid,
        },
        url: "http://10.132.20.144:8001/setUuid",
      };

      request(process).then((res) => {
        console.log(res.data);
      });
    },

    async getProgress(pro, flag) {
      // uuid = "ba079495-4319-4353-ac4d-f4c2fbf5d811";
      // pro = this.obj1;

      var url1 = "http://10.132.20.144:3000/task/" + pro.uuid + "/info";

      var url2 = "http://10.132.20.144:8001/getprocess";
      // console.log(uuid);
      if (flag == 1) {
        await axios
          .get(url1)
          .then(function (response) {
            //成功时服务器返回 response 数据
            console.log(response);
            //var percentage = response.data.progress;
            console.log(response.data.progress);
            pro.percentage = response.data.progress * 0.8;
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        process = {
          method: "post",
          data: {
            uuid: pro.uuid,
          },
          url: "http://10.132.20.144:8001/getprocess",
        };
        console.log(pro.uuid);
        request(process).then((response) => {
          console.log(response);
          //var percentage = response.data.progress;
          console.log(response.data.progress);
          pro.percentage = response.data.progress;
        });

        // axios
        //   .post(url2, uuid)
        //   .then(function (response) {
        //     //成功时服务器返回 response 数据
        //     console.log(response);
        //     //var percentage = response.data.progress;
        //     console.log(response.data.progress);
        //     pro.percentage = response.data.progress;
        //   })
        //   .catch(function (error) {
        //     console.log(error);
        //   });
      }

      if (pro.percentage < 80) {
        // clearTimeout(this.timer);
        console.log(pro.percentage);
        //setTimeout(this.getProgress(uuid, pro), 1000);
        this.getProgress(pro, flag);
      }
      if (flag == 1 && pro.percentage == 80) this.displayImages(pro);
      // this.timer = setTimeout(this.getProgress(uuid, pro), 1000);
    },
    async displayImages(pro) {
      var url = "http://10.132.20.144:8001/display";
      console.log(pro.uuid);
      // await axios.post(url, pro.uuid).then(function (response) {
      //   //成功时服务器返回 response 数据
      //   console.log(response);
      // });
      process = {
        method: "post",
        data: {
          uuid: pro.uuid,
        },
        url: "http://10.132.20.144:8001/display",
      };

      await request(process).then((res) => {
        console.log(res.data);
        // pro.address = res.data.address;
        // pro.latitude = res.data.latitude;
        // pro.longitude = res.data.longitude;
        this.iniProjects();
      });
      // var flag = 2;
      // this.getProgress(uuid, pro, flag);
      pro.percentage = 100;
      this.setPercentage(pro);
    },
    setPercentage(pro) {
      process = {
        method: "post",
        data: {
          id: pro.id,
          percentage: pro.percentage,
        },
        url: "http://10.132.20.144:8001/setPercentage",
      };

      request(process).then((res) => {
        console.log(res.data);
      });
    },

    async showResult() {
      // uuid = "d160924c-1c5a-45b0-bc79-c491ddea74ba";
      var uuid = "6fda4eed-00ac-412b-9d78-3d1ec683d182";
      console.log(uuid);

      process = {
        method: "post",
        data: {
          uuid: uuid,
        },
        url: "http://10.132.20.144:8001/display",
      };

      request(process).then((res) => {
        console.log(res.data);
      });
      // var flag = 2;
      // var pro = this.projectList[0];
      // this.getProgress(uuid, pro, flag);
    },

    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    },
    gotoHome() {
      this.$router.push("/");
    },
    onBeforeUpload(file) {
      const isIMAGE =
        file.type === "image/jpeg" || "image/gif" || "image/png" || "image/jpg";

      if (!isIMAGE) {
        this.$message.error("上传文件只能是图片格式!");
      }

      return isIMAGE;
    },
    uploadSuccess(file) {
      console.log(file);
    },
    // loading() {
    //   this.percentage += 10;
    //   console.log(this.percentage);
    //   if (this.percentage == 100) {
    //     clearInterval();
    //     return;
    //   }
    //   this.timer = setInterval(this.loading, 2000);
    // },
    loading() {
      this.percentage += 10;
      console.log(this.percentage);
      if (this.percentage == 100) {
        clearTimeout(this.timer);

        return;
      }
      this.timer = setTimeout(this.loading, 500);
    },
    cancelCreate() {
      this.dialogVisible = false;
      this.projectTitle = "";
      this.projectDiscribe = "";
    },
    iniProjects() {
      process = {
        method: "get",
        url: "http://10.132.20.144:8001/iniProject",
      };

      request(process).then((res) => {
        console.log(res.data);
        this.projectList = res.data;
      });
    },
    confirmCreate() {
      this.dialogVisible = false;
      var obj = {
        // id: 0,
        uuid: null,
        proTile: this.projectTitle,
        proDiscribe: this.projectDiscribe,
        percentage: 0,
      };
      // this.projectList.push(obj);
      this.projectTitle = "";
      this.projectDiscribe = "";
      process = {
        method: "post",
        data: {
          // id: obj.id,
          projectTitle: obj.proTile,
          proDiscribe: obj.proDiscribe,
        },
        url: "http://10.132.20.144:8001/setProject",
      };
      console.log(obj.proDiscribe);
      request(process).then((res) => {
        console.log(res.data);
        this.projectList = res.data;
      });
    },
    deleteProject(pro) {
      // console.log(index);
      // this.projectList.splice(index, 1);

      process = {
        method: "post",
        data: {
          id: pro.id,
        },
        url: "http://10.132.20.144:8001/delProject",
      };

      request(process).then((res) => {
        console.log(res.data);
        this.projectList = res.data;
      });
    },
    // submitUpload() {
    //   this.$refs.upload.submit();
    //   if (this.percentage == 100) {
    //     clearTimeout(this.timer);

    //     return;
    //   }
    //   this.timer = setTimeout(this.loadingMap, 500);
    // },
    getFile2(event) {
      let formData = new FormData();
      var uuid;
      console.log(event.target.files);
      // (this.fileList = event.target.files), console.log(this.fileList);
      //formData.append("images", event.target.files[0]);
      //formData.append("images", event.target.files[1]);
      for (var f of event.target.files) {
        formData.append("images", f);
      }

      console.log(formData);
      for (var value of formData.values()) {
        console.log(value);
      }
      const option = {
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },

        data: formData,
        url: "/receiveImg",
      };
      request(option).then((res) => {
        console.log(res);
        uuid = res.data.res;
        console.log(uuid);
      });

      while ((uuid = undefined)) {
        this.getProcess(uuid);
        break;
      }
    },
    getProcess(uuid) {
      // uuid = "e228396d-39a9-438b-aefb-bf8cf02d0efa";
      console.log(uuid);
      process = {
        method: "post",
        data: {
          uuid: uuid,
        },
        url: "/getProgress",
      };

      request(process).then((res) => {
        this.percentage = res.data.res;

        console.log(res.data.res);
        return;
      });
      console.log(this.percentage);
      if (this.percentage == 100) {
        clearTimeout(this.timer);

        return;
      }
      this.timer = setTimeout(this.getProcess, 500);
    },

    downloadPhoto(pro) {
      // var uuid = "5159d892-e764-4aec-b190-e58c28433517";
      // console.log(uuid);
      // process = {
      //   method: "get",
      //   params: {
      //     uuid: uuid,
      //   },
      //   url: "/uploadImg",
      // };

      // request(process).then((res) => {
      //   let a = document.createElement("a");
      //   console.log(res.data);
      //   //ArrayBuffer 转为 Blob
      //   //let blob = new Blob([res.data], { type: "application/x-tif" });
      //   let blob = new Blob([res.data], { type: "image/tiff" });
      //   //image/tiff
      //   let objectUrl = URL.createObjectURL(blob);
      //   a.setAttribute("href", objectUrl);
      //   a.setAttribute("download", "result.tif");
      //   a.click();
      // });

      var url =
        "http://10.132.20.144:8001/static/projects/" +
        pro.uuid +
        "/odm_orthophoto/odm_orthophoto.tif";
      let link = document.createElement("a"); //创建a标签
      link.style.display = "none"; //使其隐藏
      link.href = url; //赋予文件下载地址
      link.setAttribute("download", "result.tif"); //设置下载属性 以及文件名
      document.body.appendChild(link); //a标签插至页面中
      link.click(); //强制触发a标签事件
      document.body.removeChild(link);
    },
    downloadZip(pro) {
      // uuid = "ac6a7f2d-06d8-4f7f-a2bf-c522bce52911";
      // var url = "http://10.132.20.24:3000/task/" + uuid + "/download/all.zip";
      // let a = document.createElement("a");
      // a.href = url;
      // a.click();
      //http://10.132.20.24:3000/task/ac6a7f2d-06d8-4f7f-a2bf-c522bce52911/download/all.zip
      // var uuid = "698ec310-d0ce-4cc8-a06d-1b4185962fcc";
      var url = "http://10.132.20.144:8001/static/out.zip";
      // axios.get(url).then((file) => {
      //   let content = file.data;
      //   // 组装a标签
      //   let a = document.createElement("a");
      //   // 设置下载文件名
      //   a.download = "all.zip";
      //   a.style.display = "none";
      //   let blob = new Blob([content], { type: "application/zip" });
      //   a.href = url;
      //   //a.href = URL.createObjectURL(blob);
      //   a.target = "_self";
      //   document.body.appendChild(a);
      //   a.click();
      //   document.body.removeChild(a);

      // });
      console.log(url);
      let link = document.createElement("a"); //创建a标签
      link.style.display = "none"; //使其隐藏
      link.href = url; //赋予文件下载地址
      link.setAttribute("download", "all.zip"); //设置下载属性 以及文件名
      document.body.appendChild(link); //a标签插至页面中
      link.click(); //强制触发a标签事件
      document.body.removeChild(link);
    },
    jump2() {
      // window.location.href = "http://10.132.20.144:4200/";
      window.open("http://10.132.20.144:4200/");
    },
    gotoShowMap(pro) {
      this.$router.push({
        path: "/showMap",

        query: {
          address: pro.address,
          latitude: parseFloat(pro.latitude),
          longitude: parseFloat(pro.longitude),

          // address:
          //   "http://10.132.20.144:8001/static/d160924c-1c5a-45b0-bc79-c491ddea74ba/{z}/{x}/{y}.png",
          // latitude: parseFloat("34.03471583263848"),
          // longitude: parseFloat("108.75973423429322"),
        },
      });
    },
  },
  created() {
    // var obj1 = {
    //   uuid: null,
    //   proTile: "first",
    //   proDiscribe: "This is your first project!",
    //   percentage: 0,
    // };
    // var obj2 = {
    //   uuid: null,
    //   proTile: "second",
    //   proDiscribe: "This is your second project!",
    //   percentage: 0,
    // };
    // this.projectList.push(obj1);
    // this.projectList.push(obj2);
    this.iniProjects();
    console.log(this.projectList);
  },
};
</script>

//service docker start
//docker run -p 3000:3000 -v /home/lhg/lys/lab_back/static/projects:/var/www/data opendronemap/nodeodm
//sudo docker run -p 8001:8001 -p 3306:3306 -v /home/lhg/lys:/home/lys -it lys:18.04 /bin/bash  
//sudo docker ps -a
//sudo docker restart 96086004fe2a
//sudo docker exec -it 96086004fe2a /bin/bash
// service mysql start
//正射图像，瓦片图像